package cherry.data.service.provider;

import cherry.data.mapper.CrUserMapper;
import cherry.data.model.CrUser;
import cherry.data.service.CherryLoginService;
import cherry.data.util.Result;
import cherry.data.util.UtilDate;
import cherry.data.view.request.CherryRequest;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.ObjectUtils;
import cherry.data.service.util.SnowflakeIdUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 谢宇翔
 * @version 1.0.0
 * @ClassName CherryServiceImpl.java
 * @Description 接口实现
 * @createTime 2022年01月06日 23:53:00
 */
@Log4j2
@RestController
public class CherryLoginServiceImpl implements CherryLoginService {

    @Resource
    private CrUserMapper userMapper;

    //生成id工具
    SnowflakeIdUtils idWorker = new SnowflakeIdUtils(3, 1);

    /**
     * @ClassName CherryServiceImpl.java
     * @author 谢宇翔
     * @version 1.0.0
     * @Description 登录接口
     * @createTime 2022年01月06日 23:53:00
     */
    @Override
    public Result<?> logIns(@RequestBody CherryRequest request) {
        String userAccount = request.getUserAccount();
        String password = request.getPassword();
        if (UtilDate.isLetterDigit(password)) {
            return new Result<>(901, "请按照规则填写密码（包含大小写字母及数字且在6-12位）");
        }
        log.info("登录账号：" + userAccount+ "登录密码：" + password);
        CrUser crUser = userMapper.selectLog(userAccount, password);
        if (ObjectUtils.isEmpty(crUser)) {
            return new Result<>(901, "登录失败,账号密码错误");
        }
        return new Result<>(600,"登录成功",crUser);
    }

    /**
     * @ClassName CherryServiceImpl.java
     * @author 谢宇翔
     * @version 1.0.0
     * @Description 注册注册
     * @createTime 2022年01月07日 22:29:00
     */
    @Override
    public Result<?> register(@RequestBody CherryRequest request) {
        if (UtilDate.isLetterDigit(request.getPassword())) {
            return new Result<>(901, "请按照规则填写密码（包含大小写字母及数字且在6-12位）");
        }
        //判断账号已经存在
        CrUser crUser = userMapper.userNameOnlyEmail( request.getUserAccount());
        if (!ObjectUtils.isEmpty(crUser)) {
            return new Result<>(902, "用户名，邮箱已存在");
        }
        log.info("进入server的参数：" + request);
        CrUser user = new CrUser();
        user.setId(idWorker.nextId());
        user.setFlag(1);
        user.setCreateTime(new Date());
        user.setCreatorId(100L);
        user.setName(request.getName());
        user.setPassword(request.getPhone());
        user.setUserAccount(request.getUserAccount());
        user.setPassword(request.getPassword());
        int register = userMapper.create(user);
        log.info("是否成功：" + register);
        if (ObjectUtils.isEmpty(register)) {
            return null;
        }
        return Result.success(600);
    }
}
